/**
 * 引入需要用到的模块
 * */
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var RedisStore = require('connect-redis')(session);
var request = require('request-json');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var order = require('./routes/order');
var app = express();

/**
 * log4日志配置start
 * */
// var log4js = require('log4js');
//
// var oDate = new Date(); //实例一个时间对象f；
// var data=oDate.getFullYear()+"-"+(parseInt(oDate.getMonth())+1)+"-"+oDate.getDate()+"-"+oDate.getHours();
//
// log4js.configure({
//     "appenders": [{
//         "type": "file",
//         "filename": __dirname + "/logs/errorlogger"+data+".log",
//         "pattern": "-yyyy-MM-dd-hh.log",
//         "alwaysIncludePattern": true,
//         "category": "errorlogger",
//         "maxLogSize": 10 * 1024 * 1024,
//         "numBackups": 5,
//     },
//         {
//             "type": "file",
//             "filename": __dirname + "/logs/infologger"+data+".log",
//             "pattern": "-yyyy-MM-dd-hh.log",
//             "alwaysIncludePattern": true,
//             "category": "infologger",
//             "maxLogSize": 10 * 1024 * 1024,
//             "numBackups": 5,
//         },
//         {
//             "type": "console",
//         },
//     ],
//     "levels": {
//         "errorlogger": "ERROR",
//         "infologger": "INFO"
//
//     }
// });
// var logger = log4js.getLogger('errorlogger');
// app.use(log4js.connectLogger(log4js.getLogger('errorlogger')));
// app.use(log4js.connectLogger(log4js.getLogger('infologger')));

/**
 * log4日志配置end
 * */

/**
 * 设置静态文件存放在views
 * 静态页面使用jade格式
 * */
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

/**
 * 接口地址
 * */
var client = request.createClient('http://settledapi.eduoln.com/');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

/**
 * 缓存服务器的设置
 * */
app.use(session({
  store: new RedisStore({
    host: '118.190.94.144',
    port: 6379,
    pass:'Yuwei2016'
  }),
  resave: false,
  saveUninitialized: false,
  secret: 'hyjfExpress',
  cookie: {maxAge: 60 * 60 * 1000 * 24}
}));

app.use(function (req, res, next) {
  req.client = client;
  req.c = function (cb) {
    return function (c_err, c_res, c_body) {
      cb(c_err, c_body.info);
    };
  };
  next();
});

app.use(function (req, res, next) {
  res.locals.user = req.session.user || null;
  next();
});

app.use('/', index);
app.use('/order', order);

/**
 * 捕捉404状态下进入到error页面
 * */
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    var deviceAgent = req.headers["user-agent"].toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);
    if(agentID){
      res.render('appError', {
        message: err.message,
        error: err
      });
    }else{
      res.render('error', {
        message: err.message,
        error: err
      });
    }
  });
}

app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  var deviceAgent = req.headers["user-agent"].toLowerCase();
  var agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);
  if(agentID){
    res.render('appError', {
      message: err.message,
      error: err
    });
  }else{
    res.render('error', {
      message: err.message,
      error: err
    });
  }
});

module.exports = app;
